/**
 * 菜单管理模块 - 管理一级菜单、二级菜单和浮动菜单
 */
const MenuManager = {
    // DOM引用
    primaryMenuItemsContainer: null,
    primaryMenuItems: null,
    secondaryMenuItemsContainer: null,
    floatingMenuContainer: null,
    floatingMenuContent: null,

    // 状态
    currentPrimaryMenuId: '', // 初始化时获取一级菜单[0]
    floatingMenuHideTimeout: null, // 隐藏浮动菜单的定时器
    isFloatingMenuHovered: false, // 浮动菜单是否被鼠标悬停

    /**
     * 初始化
     */
    init() {
        // 获取DOM引用
        this.primaryMenuItemsContainer = document.querySelector(
            '.primary-menu-items'
        );
        this.secondaryMenuItemsContainer = document.querySelector(
            '.secondary-menu-items'
        );
        this.floatingMenuContainer = document.getElementById('floatingMenu');
        this.floatingMenuContent = document.getElementById(
            'floatingMenuContent'
        );

        // 设置currentPrimaryMenuId为第一个顶级一级菜单ID
        const topLevelPrimaryMenus = applicationMenuData.filter(
            (item) => item.parentId === ''
        );
        if (topLevelPrimaryMenus.length > 0) {
            this.currentPrimaryMenuId = topLevelPrimaryMenus[0].id;
        }

        // 动态渲染一级菜单
        this.renderPrimaryMenu();

        // 设置事件监听
        this._setupEvents();

        // 初始化显示第一个一级菜单的二级菜单
        this.renderSecondaryMenu(this.currentPrimaryMenuId);
    },

    /**
     * 事件监听
     * @private
     */
    _setupEvents() {
        // 一级菜单项点击事件 - 因为是动态生成的，这个事件监听需要在renderPrimaryMenu后重新设置
        // 但由于我们在setupEvents之前调用了renderPrimaryMenu，所以这里可以正常工作
        this.primaryMenuItems.forEach((item) => {
            Utils.on(item, 'click', () => {
                const primaryMenuId = item.dataset.primaryMenuId;
                if (!primaryMenuId) return;

                this.primaryMenuItems.forEach((menuItem) =>
                    menuItem.classList.remove('active')
                );
                item.classList.add('active');

                this.currentPrimaryMenuId = primaryMenuId;
                this.renderSecondaryMenu(primaryMenuId);
            });
        });

        // 浮动菜单鼠标事件
        Utils.on(this.floatingMenuContainer, 'mouseenter', () => {
            if (this.floatingMenuHideTimeout) {
                clearTimeout(this.floatingMenuHideTimeout);
            }
            this.isFloatingMenuHovered = true;
        });

        Utils.on(this.floatingMenuContainer, 'mouseleave', () => {
            this.isFloatingMenuHovered = false;
            this.hideFloatingMenu();
        });
    },

    /**
     * 渲染一级菜单
     */
    renderPrimaryMenu() {
        if (!this.primaryMenuItemsContainer) return;

        // 清空容器
        this.primaryMenuItemsContainer.innerHTML = '';

        // 获取所有顶级一级菜单（parentId为空的项）
        const topLevelPrimaryMenus = applicationMenuData.filter(
            (item) => item.parentId === ''
        );

        topLevelPrimaryMenus.forEach((primaryMenu) => {
            const menuItem = document.createElement('div');
            menuItem.className = 'primary-menu-item';

            // 设置默认选中第一个一级菜单
            if (primaryMenu.id === this.currentPrimaryMenuId) {
                menuItem.classList.add('active');
            }

            // 设置一级菜单ID
            menuItem.dataset.primaryMenuId = primaryMenu.id;

            // 构建菜单项HTML
            let iconHtml = '';
            // 检查是否有二级菜单
            const hasChildren = applicationMenuData.some(
                (item) => item.parentId === primaryMenu.id
            );

            if (primaryMenu.icon) {
                iconHtml = `<i class="fas ${primaryMenu.icon} menu-icon"></i>`;
            } else {
                // 根据是否有下级设置不同的默认图标
                if (hasChildren) {
                    iconHtml = '<i class="fas fa-th-large menu-icon"></i>'; // 有下级用网格图标
                } else {
                    iconHtml = '<i class="fas fa-file-lines menu-icon"></i>'; // 没有下级用文件图标（Font Awesome 6兼容）
                }
            }

            menuItem.innerHTML = `
                ${iconHtml}
                <span class="menu-label">${primaryMenu.displayName}</span>
            `;

            this.primaryMenuItemsContainer.appendChild(menuItem);
        });

        // 更新primaryMenuItems引用
        this.primaryMenuItems = document.querySelectorAll('.primary-menu-item');
    },

    /**
     * 渲染二级菜单
     * @param {string} primaryMenuId - 一级菜单的唯一标识符
     */
    renderSecondaryMenu(primaryMenuId) {
        const primaryMenuItem = applicationMenuData.find(
            (item) => item.id === primaryMenuId && item.parentId === ''
        );
        if (!primaryMenuItem || !this.secondaryMenuItemsContainer) return;

        this.secondaryMenuItemsContainer.innerHTML = '';

        // 获取该一级菜单的直接子项（二级菜单）
        const secondaryMenuItems = applicationMenuData.filter(
            (item) => item.parentId === primaryMenuItem.id
        );

        secondaryMenuItems.forEach((secondaryMenuItem) => {
            // 检查是否有下级菜单（即是否有第三级菜单）
            const hasSubmenu = applicationMenuData.some(
                (item) => item.parentId === secondaryMenuItem.id
            );

            const menuItem = document.createElement('div');
            menuItem.className = 'secondary-menu-item';
            if (hasSubmenu) {
                menuItem.classList.add('has-submenu');
            }

            // 构建菜单项HTML
            let iconHtml = '';

            if (secondaryMenuItem.icon) {
                iconHtml = `<i class="fas ${secondaryMenuItem.icon} folder-icon"></i>`;
            } else {
                // 根据是否有下级设置不同的默认图标
                if (hasSubmenu) {
                    iconHtml = '<i class="fas fa-folder folder-icon"></i>'; // 有下级用文件夹图标
                } else {
                    iconHtml = '<i class="fas fa-file-lines folder-icon"></i>'; // 没有下级用文件图标（Font Awesome 6兼容）
                }
            }

            menuItem.innerHTML = `
                ${iconHtml}
                <span class="item-label">${secondaryMenuItem.displayName}</span>
                ${hasSubmenu
                    ? '<i class="fas fa-chevron-right chevron-icon"></i>'
                    : ''
                }
            `;
            menuItem.dataset.secondaryMenuId = secondaryMenuItem.id;
            menuItem.dataset.hasSubmenu = hasSubmenu;

            if (hasSubmenu) {
                Utils.on(menuItem, 'mouseenter', () => {
                    this.renderFloatingMenu(
                        menuItem,
                        primaryMenuItem.id,
                        secondaryMenuItem.id
                    );
                });
                
                Utils.on(menuItem, 'mouseleave', () => {
                    this.hideFloatingMenu();
                });
            }

            Utils.on(menuItem, 'click', (e) => {
                // 阻止事件冒泡，避免触发父容器的关闭浮动菜单事件
                e.stopPropagation();

                // 处理带有二级菜单的菜单项的点击事件
                if (hasSubmenu) {
                    // 检查浮动菜单是否已经显示且是当前菜单项的浮动菜单
                    const isFloatingMenuVisible =
                        this.floatingMenuContainer &&
                        this.floatingMenuContainer.style.display === 'block';
                    const currentMenuId =
                        this.floatingMenuContent?.dataset.secondaryMenuId;
                    const isCurrentMenuItemFloatingMenu =
                        currentMenuId === secondaryMenuItem.id;

                    // 优化：将重复的隐藏操作提取到条件判断之前
                    this.hideFloatingMenuImmediately();
                    
                    // 仅在不是当前显示的浮动菜单时才渲染新菜单
                    if (!(isFloatingMenuVisible && isCurrentMenuItemFloatingMenu)) {
                        this.renderFloatingMenu(
                            menuItem,
                            primaryMenuItem.id,
                            secondaryMenuItem.id
                        );
                        // 记录当前浮动菜单对应的二级菜单ID
                        if (this.floatingMenuContent) {
                            this.floatingMenuContent.dataset.secondaryMenuId = secondaryMenuItem.id;
                        }
                    }
                } else if (secondaryMenuItem.url) {
                    // 如果没有二级菜单但有路径，则打开标签页
                    TabManager.addNewTab(
                        secondaryMenuItem.displayName,
                        secondaryMenuItem.url
                    );
                }
            });

            this.secondaryMenuItemsContainer.appendChild(menuItem);
        });

        // 二级菜单显示逻辑已经通过CSS默认设置
    },

    /**
     * 渲染浮动菜单（三级菜单）
     * @param {HTMLElement} secondaryMenuItemEl - 二级菜单项元素
     * @param {string} primaryMenuId - 一级菜单的ID
     * @param {string} secondaryMenuId - 二级菜单的ID
     */
    renderFloatingMenu(secondaryMenuItemEl, primaryMenuId, secondaryMenuId) {
        // 清除之前的隐藏超时
        if (this.floatingMenuHideTimeout) {
            clearTimeout(this.floatingMenuHideTimeout);
        }

        // 获取菜单数据并验证
        const primaryMenuItem = applicationMenuData.find(
            (item) => item.id === primaryMenuId && item.parentId === ''
        );
        const secondaryMenuItem = applicationMenuData.find(
            (item) => item.id === secondaryMenuId
        );

        // 验证必要的元素和数据存在性
        if (
            !primaryMenuItem ||
            !secondaryMenuItem ||
            !this.floatingMenuContent ||
            !this.floatingMenuContainer ||
            !document.querySelector('.sidebar-container')
        ) {
            return;
        }

        // 获取位置信息并清空内容
        const sidebarContainer = document.querySelector('.sidebar-container');
        const sidebarContainerRect = sidebarContainer.getBoundingClientRect();
        const rect = secondaryMenuItemEl.getBoundingClientRect();
        this.floatingMenuContent.innerHTML = '';

        // 获取三级菜单
        const thirdlyMenuItems = applicationMenuData.filter(
            (item) => item.parentId === secondaryMenuId
        );

        // 分离三级菜单：有/无子菜单的
        const thirdlyMenuWithChildren = thirdlyMenuItems.filter((item) =>
            applicationMenuData.some((child) => child.parentId === item.id)
        );
        const thirdlyMenuWithoutChildren = thirdlyMenuItems.filter(
            (item) =>
                !applicationMenuData.some((child) => child.parentId === item.id)
        );

        // 渲染标题区域，使用二级菜单名称作为标题
        let directAccessItemsCount = 0;
        // 只有在混合情况下才将无子菜单的三级菜单项放在标题区域
        const directAccessItems =
            thirdlyMenuWithChildren.length > 0 &&
                thirdlyMenuWithoutChildren.length > 0
                ? thirdlyMenuWithoutChildren
                : [];

        this._renderHeaderSection(secondaryMenuItem, directAccessItems);
        directAccessItemsCount = directAccessItems.length;

        // 创建列容器
        const columnsContainer = document.createElement('div');
        columnsContainer.className = 'floating-menu-columns';

        // 渲染菜单列
        const filteredThirdlyMenuWithoutChildren =
            directAccessItemsCount > 0
                ? [] // 已经在标题区域显示
                : thirdlyMenuWithoutChildren;

        this._renderMenuColumns(
            columnsContainer,
            thirdlyMenuWithChildren,
            filteredThirdlyMenuWithoutChildren
        );

        // 添加列容器到内容容器
        this.floatingMenuContent.appendChild(columnsContainer);
        
        // 记录当前浮动菜单对应的二级菜单ID
        this.floatingMenuContent.dataset.secondaryMenuId = secondaryMenuId;

        // 设置宽度和位置
        this._setMenuWidth(
            thirdlyMenuWithChildren,
            filteredThirdlyMenuWithoutChildren
        );
        this._setMenuPosition(sidebarContainerRect, rect);
    },

    // 创建菜单项元素
    _createMenuItem(item, className = 'floating-menu-item') {
        const menuItem = document.createElement('div');
        menuItem.className = className;
        menuItem.textContent = item.displayName;
        menuItem.dataset.menuId = item.id;

        Utils.on(menuItem, 'click', () => {
            if (item.url && item.url.trim() !== '') {
                TabManager.addNewTab(item.displayName, item.url);
            }
            this.hideFloatingMenuImmediately();
        });

        return menuItem;
    },

    // 渲染标题区域
    _renderHeaderSection(secondaryMenuItem, directAccessItems) {
        const headerContainer = document.createElement('div');
        headerContainer.className = 'floating-menu-header';

        // 添加标题
        const headerText = document.createElement('div');
        headerText.className = 'floating-menu-header-text';
        headerText.textContent = secondaryMenuItem.displayName;
        headerContainer.appendChild(headerText);

        // 添加直接访问项
        const directAccessContainer = document.createElement('div');
        directAccessContainer.className = 'floating-menu-header-items';

        directAccessItems.forEach((item) => {
            directAccessContainer.appendChild(
                this._createMenuItem(item, 'floating-menu-header-item')
            );
        });

        headerContainer.appendChild(directAccessContainer);
        this.floatingMenuContent.appendChild(headerContainer);
    },

    // 渲染菜单列
    _renderMenuColumns(
        columnsContainer,
        thirdlyMenuWithChildren,
        thirdlyMenuWithoutChildren
    ) {
        // 情况1：只有三级菜单（没有四级菜单）
        if (
            thirdlyMenuWithChildren.length === 0 &&
            thirdlyMenuWithoutChildren.length > 0
        ) {
            const columnDiv = document.createElement('div');
            columnDiv.className = 'floating-menu-column';

            // 添加菜单项
            thirdlyMenuWithoutChildren.forEach((item) => {
                columnDiv.appendChild(this._createMenuItem(item));
            });

            columnsContainer.appendChild(columnDiv);
        } else {
            // 情况2：有四级菜单
            // 渲染带四级菜单的列
            thirdlyMenuWithChildren.forEach((thirdlyMenuItem) => {
                const columnDiv = document.createElement('div');
                columnDiv.className = 'floating-menu-column';

                // 检查是否需要渲染标题 - 基于菜单列数量的逻辑
                // 计算总列数：带四级菜单的列数 + 无子菜单三级菜单的列数（如果有）
                const totalColumns =
                    thirdlyMenuWithChildren.length +
                    (thirdlyMenuWithoutChildren.length > 0 ? 1 : 0);

                // 只有当总列数大于1时才渲染标题，单列情况下不渲染标题
                if (totalColumns > 1) {
                    const title = document.createElement('div');
                    title.className = 'floating-menu-title';
                    title.textContent = thirdlyMenuItem.displayName;
                    columnDiv.appendChild(title);
                }

                // 获取并渲染四级菜单
                const fourthlyMenuItems = applicationMenuData.filter(
                    (item) => item.parentId === thirdlyMenuItem.id
                );

                fourthlyMenuItems.forEach((item) => {
                    columnDiv.appendChild(this._createMenuItem(item));
                });

                columnsContainer.appendChild(columnDiv);
            });

            // 渲染无下级的三级菜单列
            if (thirdlyMenuWithoutChildren.length > 0) {
                const columnDiv = document.createElement('div');
                columnDiv.className = 'floating-menu-column';

                thirdlyMenuWithoutChildren.forEach((item) => {
                    columnDiv.appendChild(this._createMenuItem(item));
                });

                columnsContainer.appendChild(columnDiv);
            }
        }
    },

    // 设置菜单宽度
    _setMenuWidth(thirdlyMenuWithChildren, thirdlyMenuWithoutChildren) {
        // 计算列数
        let columnCount = 0;
        if (
            thirdlyMenuWithChildren.length === 0 &&
            thirdlyMenuWithoutChildren.length > 0
        ) {
            columnCount = 1;
        } else {
            columnCount = thirdlyMenuWithChildren.length;
            if (thirdlyMenuWithoutChildren.length > 0) {
                columnCount++;
            }
        }

        // 设置宽度（每列160px）
        const columnWidth = 160;
        this.floatingMenuContainer.style.width =
            columnCount * columnWidth + 'px';
    },

    // 设置菜单位置
    _setMenuPosition(sidebarContainerRect, rect) {
        // 初始位置
        this.floatingMenuContainer.style.left =
            sidebarContainerRect.right + 1 + 'px';
        this.floatingMenuContainer.style.top = rect.top + 'px';
        this.floatingMenuContainer.style.display = 'block';

        // 调整位置避免超出视口
        const viewportWidth = window.innerWidth;
        const viewportHeight = window.innerHeight;
        const floatingMenuContainerRect =
            this.floatingMenuContainer.getBoundingClientRect();

        // 水平调整
        if (floatingMenuContainerRect.right > viewportWidth) {
            const overflow = floatingMenuContainerRect.right - viewportWidth;
            this.floatingMenuContainer.style.left =
                sidebarContainerRect.right - overflow - 10 + 'px';
        }

        // 垂直调整
        if (floatingMenuContainerRect.bottom > viewportHeight) {
            const overflow = floatingMenuContainerRect.bottom - viewportHeight;
            this.floatingMenuContainer.style.top =
                rect.top - overflow - 10 + 'px';
        }

        // 确保不小于顶部边界
        if (parseInt(this.floatingMenuContainer.style.top) < 0) {
            this.floatingMenuContainer.style.top = '10px';
        }
    },

    /**
     * 延迟隐藏浮动菜单
     */
    hideFloatingMenu() {
        if (this.floatingMenuHideTimeout) {
            clearTimeout(this.floatingMenuHideTimeout);
        }
        this.floatingMenuHideTimeout = setTimeout(() => {
            if (!this.isFloatingMenuHovered && this.floatingMenuContainer) {
                this.floatingMenuContainer.style.display = 'none';
            }
        }, 200);
    },

    /**
     * 立即隐藏浮动菜单
     */
    hideFloatingMenuImmediately() {
        if (this.floatingMenuHideTimeout) {
            clearTimeout(this.floatingMenuHideTimeout);
        }
        if (this.floatingMenuContainer) {
            this.floatingMenuContainer.style.display = 'none';
        }
        this.isFloatingMenuHovered = false;
    },
};

// 导出模块
if (typeof module !== 'undefined') {
    module.exports = { MenuManager };
}
